package com.nuoniu.sibanyun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.config.YmlConfig;
import com.nuoniu.sibanyun.entity.SysCompany;
import com.nuoniu.sibanyun.entity.SysUser;
import com.nuoniu.sibanyun.entity.cms.CmsInfo;
import com.nuoniu.sibanyun.entity.crm.CrmGoods;
import com.nuoniu.sibanyun.entity.crm.CrmSecretKey;
import com.nuoniu.sibanyun.entity.dto.SysCompanyDto;
import com.nuoniu.sibanyun.mapper.SysCompanyMapper;
import com.nuoniu.sibanyun.mapper.SysUserMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmGoodsMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmSecretKeyMapper;
import com.nuoniu.sibanyun.service.ISysCompanyService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 公司表 服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-04-23
 */
@Service
public class SysCompanyServiceImpl extends ServiceImpl<SysCompanyMapper, SysCompany> implements ISysCompanyService {

    @Autowired
    private SysCompanyMapper companyMapper;
    @Autowired
    private CrmSecretKeyMapper secretKeyMapper;
    @Autowired
    private CrmGoodsMapper goodsMapper;
    @Autowired
    private SysUserMapper userMapper;

    @Override
    public Map getCompanyInfo(Integer companyId) {
        Map data = companyMapper.getCompanyInfo(companyId);
        if(data != null) {
            data.put("entryUrl", YmlConfig.ENTRY_URL + "?cId=" + data.get("id") + "&code=" + data.get("companyCode"));
            if(data.get("secretKeyId") != null) {
                CrmSecretKey secretKey = secretKeyMapper.selectById(data.get("secretKeyId").toString());
                if(secretKey != null) {
                    data.put("goodsName", secretKey.getGoodsName());
                    data.put("goodsId", secretKey.getGoodsId());
                    data.put("type", secretKey.getType());
                    data.put("endDate", DateTimeFormatter.ofPattern("yyyy-MM-dd").format(secretKey.getEndDate()));
                    Integer endMonth = secretKey.getEndDate().getYear() * 12 + secretKey.getEndDate().getMonthValue();
                    Integer useMonth = LocalDateTime.now().getYear() * 12 + LocalDateTime.now().getMonthValue();
                    if(endMonth - useMonth > 0) {
                        data.put("months", endMonth - useMonth);
                    }else {
                        data.put("months", 0);
                    }
                    data.put("goods", goodsMapper.selectById(secretKey.getGoodsId()));
                }
            }
        }
        return data;
    }

    @Override
    public void updateSecretKey(CrmSecretKey secretKey) {
        UserInfo userInfo = UserThreadLocal.get();
        if(secretKey.getUseDate() == null) {
            secretKey.setUseDate(LocalDateTime.now());
            secretKey.setEndDate(LocalDateTime.now().plusYears(secretKey.getYears()));
        }

        secretKey.setUseTimes(secretKey.getUseTimes() + 1);
        secretKeyMapper.updateById(secretKey);

        SysCompany company = this.getById(userInfo.getCompanyId());
        company.setSecretKeyId(secretKey.getId().intValue());
        company.setSecretKey(secretKey.getSecretKey());
        company.setCompanyUser(secretKey.getUsers());

        List<UserInfo> userList = userMapper.getUserList(userInfo.getCompanyId());
        Integer users = userList.size() - (company.getCompanyUser() + company.getFreeUser());
        if(users > 0) { //多余用户数停用
            Integer roleId = 9;
            if(company.getGoodsId() != null) {
                CrmGoods goods = goodsMapper.selectById(company.getGoodsId());
                roleId = goods.getRoleId();
            }

            //处理该公司正在使用的用户
            SysUser user = userMapper.getSysManager(company.getId().intValue(), roleId);
            userMapper.updateStatus(company.getId(), userList.size(), company.getCompanyUser() + company.getFreeUser() - 1, user.getId());
        }
        this.updateById(company);
    }

    @Override
    public SysCompany getByName(String companyNme) {
        return companyMapper.getByName(companyNme);
    }

    @Override
    public Page<SysCompany> pageList(Page page, SysCompany company) {
        return companyMapper.pageList(page, company);
    }

    @Override
    @Async
    public void updateFreeUsers(Integer freeUsers) {
        companyMapper.updateFreeUsers(freeUsers);
        List<SysCompany> companyList = companyMapper.getAll();
        for(SysCompany company : companyList) {
            List<UserInfo> userList = userMapper.getUserList(company.getId().intValue());
            Integer users = userList.size() - (company.getCompanyUser() + freeUsers);
            if(users > 0) { //多余用户数停用
                Integer roleId = 9;
                if(company.getGoodsId() != null) {
                    CrmGoods goods = goodsMapper.selectById(company.getGoodsId());
                    roleId = goods.getRoleId();
                }

                //处理该公司正在使用的用户
                SysUser user = userMapper.getSysManager(company.getId().intValue(), roleId);
                userMapper.updateStatus(company.getId(), userList.size(), company.getCompanyUser() + freeUsers - 1, user.getId());
            }
        }
    }

    @Override
    public Map<String, String> getEntryCompany(String cId, String code) {
        return companyMapper.getEntryCompany(cId, code);
    }

    @Override
    public SysCompanyDto getSysCompany(Integer companyId) {
        return companyMapper.getSysCompany(companyId);
    }

    @Override
    public SysCompany getByCode(String companyCode) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("companyCode", companyCode);
        wrapper.last("LIMIT 1");
        return getOne(wrapper);
    }
}
